<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/user'
import { getUserOrders } from '../../api/user'
import { showDialog, showToast } from 'vant'

const router = useRouter()
const userStore = useUserStore()

// 用户订单列表
const orderList = ref<any[]>([])
// 加载状态
const loading = ref(false)
// 下拉刷新
const refreshing = ref(false)

// 获取用户订单
const fetchUserOrders = async () => {
  try {
    if (!userStore.userId) {
      showToast('获取用户ID失败')
      return
    }
    
    loading.value = true
    const res = await getUserOrders(userStore.userId)
    orderList.value = res.data || []
  } catch (error: any) {
    showToast(error.message || '获取订单失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  fetchUserOrders()
}

// 查看订单详情
const viewOrderDetail = (id: string) => {
  router.push(`/order/detail/${id}`)
}

// 退出登录
const logout = () => {
  showDialog({
    title: '提示',
    message: '确定要退出登录吗？',
    showCancelButton: true
  }).then(() => {
    userStore.logout()
    router.push('/login')
  }).catch(() => {
    // 取消操作
  })
}

// 页面初始化
onMounted(() => {
  fetchUserOrders()
})
</script>

<template>
  <div class="profile-container">
    <van-nav-bar title="个人中心" />
    
    <!-- 用户信息 -->
    <div class="user-info">
      <van-image
        round
        width="80"
        height="80"
        :src="userStore.userInfo.avatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
      />
      <div class="user-name">{{ userStore.userInfo.username || '用户' }}</div>
      <div class="user-phone">{{ userStore.userInfo.email || '' }}</div>
    </div>
    
    <!-- 操作菜单 -->
    <van-cell-group inset class="action-group">
      <van-cell title="我的订单" is-link @click="router.push('/order/list')" />
    </van-cell-group>
    
    <van-cell-group inset class="action-group">
      <van-cell title="退出登录" is-link @click="logout" />
    </van-cell-group>
   
  </div>
</template>

<style scoped>
.profile-container {
  min-height: 100%;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

.user-info {
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
}

.user-name {
  margin-top: 10px;
  font-size: 18px;
  font-weight: bold;
}

.user-phone {
  margin-top: 5px;
  font-size: 14px;
  color: #969799;
}

.action-group {
  margin-top: 12px;
}

.recent-orders {
  margin-top: 12px;
}

.section-title {
  padding: 0 16px;
  margin: 16px 0 8px;
  font-size: 14px;
  color: #969799;
}

.empty-list {
  text-align: center;
  padding: 40px 0;
  color: #969799;
}

.order-status {
  font-size: 14px;
  color: #1989fa;
}
</style> 